package FloodFill;

import java.util.LinkedList;
import java.util.Queue;

public class Solve {
    int[] dx = new int[]{0, 0, 1, -1};
    int[] dy = new int[]{1, -1, 0, 0};
    int m, n;

    public void code(char[][] board) {
        m = board.length;
        n = board[0].length;

        for (int j = 0; j < n; j++){
            if (board[0][j] == 'O'){
                bfs(board, 0, j);
            }

            if (board[m - 1][j] == 'O'){
                bfs(board, m - 1, j);
            }
        }

        for (int j = 0; j < m; j++){
            if (board[j][0] == 'O'){
                bfs(board, j, 0);
            }

            if (board[j][n - 1] == 'O'){
                bfs(board, j, n - 1);
            }
        }

        //还原
        for (int i = 0; i < m; i++){
            for (int j = 0; j < n; j++){
                if (board[i][j] == 'O'){
                    board[i][j] = 'X';
                }else if (board[i][j] == '.'){
                    board[i][j] = 'O';
                }
            }
        }
    }

    public void bfs(char[][] board, int i, int j){
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{i, j});
        board[i][j] = '.';

        while (!q.isEmpty()){
            int[] t = q.poll();

            for (int k = 0; k < 4; k++){
                int x = t[0] + dx[k], y = t[1] + dy[k];

                if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O'){
                    board[x][y] = '.';
                    q.add(new int[]{x, y});
                }
            }

        }
    }

    public static void main(String[] args) {
        Solve test = new Solve();
        char[][] tmp = new char[][]{{'X','X','X','X'},{'X','O','O','X'},{'X','X','O','X'},{'X','O','X','X'}};
        test.code(tmp);
    }
}
